<template>
    <fieldset>
        <legend>三级联动</legend>
        省：
        <select v-model="sel1" @change="provinceChange(sel1)">
            <option v-for="item in province" :key="item.id" :value="item.id">{{ item.name }}</option>
        </select>
        市：
        <select v-model="sel2" @change="areaChange(sel2)">
            <option v-for="item in citys" :key="item.id" :value="item.id">{{ item.name }}</option>
        </select>
        区:
        <select v-model="sel3">
            <option v-for="item in areas" :key="item.id" :value="item.id">{{ item.name }}</option>
        </select>
    </fieldset>
</template>


<script>
import * as api from '@/api/select'
import axios from 'axios'
export default {
    data() {
        return {
            province: [],
            sel1: 1,
            sel2: '',
            sel3:'',
            citys: [],
            areas: []
        }
    },
    mounted() {
        api.fetchData()
            .then(res => {
                console.log(res);
                this.province = res
                // 获取默认第一条的id
                let pid = res[0].id
                this.provinceChange(pid)
            })

    },
    methods: {
        provinceChange(pid) {
            api.fetchCity(pid)
                .then(res => {
                    console.log(res);
                    this.citys = res;
                    // 设置市默认值
                    if (res.length > 0) {
                        this.sel2 = res[0].id
                    }
                    let cityId = res[0].id
                    this.areaChange(cityId)
                })
        },
        areaChange(cityId) {
            api.fetchArea(cityId)
                .then(res => {
                    console.log(res);
                    this.areas = res
                    // 设置区默认值
                    if (res.length > 0) {
                        this.sel3 = res[0].id
                    }
                    

                })
            // axios.get("/province.json")   
            // .then(res=>{
            //     console.log(res.data.data);
            //     let a1=res.data.data.filter(item=>item.parentId===4);
            //     console.log(a1);
            //     this.areas=a1
            // })


        }
    }

}






</script>

<style scoped>
select {
    width: 100px;

}
</style>